var config = require('../config/config');
var Notify = require('../proxy/Notify');

/**
 * 需要管理员权限
 */
exports.adminRequired = function(req, res, next) {
	if (!req.session.user) {
		// return res.render('notify/notify', {
		// 	error: '你还没有登录。'
		// });
		var _referrer = backurl(req);
		return res.redirect('/sign/signin' + '?backurl=' + _referrer);
	}
	if (!req.session.user.is_admin) {
		return res.render('notify/notify', {
			error: '管理员才能编辑标签。'
		});
	}
	next();
};

/**
 * 需要登录
 */
exports.userRequired = function(req, res, next) {
	if (!req.session || !req.session.user) {
		return res.send(403, 'forbidden!');
	}
	next();
};

/**
 * 需要登录，响应错误页面
 */
exports.signinRequired = function(req, res, next) {
	if (!req.session.user) {
		// res.render('notify/notify', {
		// 	error: '你还没有<a href=\'/sign/signin\'>登录</a>。'
		// });
		// console.log(req);
		var _referrer = backurl(req);
		res.redirect('/sign/signin' + '?backurl=' + _referrer);
		return;
	}
	next();
};

exports.blockUser = function() {
	return function(req, res, next) {
		if (req.session.user && req.session.user.is_block) {
			return res.send('您被屏蔽了。');
		}
		next();
	};
}


/**
 * 不能登录
 */
exports.canNotSignin = function(req, res, next) {
	if (req.session.user) {
		res.redirect('/');
		return;
	}
	next();
};

// auth_user middleware
exports.authUser = function(req, res, next) {
	if (req.session.user) {
		// if (config.admins.hasOwnProperty(req.session.user.name)) {
		//   req.session.user.is_admin = true;
		// }
		// 查询用户有没有通知
		Notify.getUserNotify(req.session.user._id, function(err, notifies) {
			if (err) return next(err);
			if (notifies) {
				// for(var i=0; i<notifies.length; i++){
				//   notifies[i].friendly_create_at = Util.format_date(notifies[i].create_at, true);
				// }
				res.locals.notifies = notifies;
			}
		});
		// 将用户从session中放到locals中
		res.locals.current_user = req.session.user;
	}
	return next();
};

function backurl(req) {
	var _hostname = req.hostname || req.host;
	var port = process.env.PORT || config.app.port;
	var securePort = process.env.SECURE_PORT || config.app.securePort;
	var url = req.originalUrl;
	if (req.secure) {
		if (securePort === 443) {
			return encodeURIComponent('https://' + _hostname + url);
		} else {
			return encodeURIComponent('https://' + _hostname + ':' + securePort + url);
		}
	} else {
		if (port === 80) {
			return encodeURIComponent('http://' + _hostname + url);
		} else {
			return encodeURIComponent('http://' + _hostname + ':' + port + url);
		}
	}
}